<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" append-to-body width="750" destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
		<el-steps align-center :active="validStep" simple class="steps">
			<el-step v-for="(step, i) in validOptions" :title="step.title" :key="i"
					 :icon="step.icon" :status="step.status" :description="step.description"/>
		</el-steps>
		<div style="margin: 0px auto;padding: 30px 0px;text-align: center; position: relative;" v-if="validStep < 4">
			<div v-if="validStatus" style="position: absolute; top: 72px;left: 282px;">
				<el-icon style="font-size: 26px;background: 0px; animation: rotating 2s linear infinite; fill: rgba(255,255,255,0.87);" class="app-icon">
					<component :is="icon"></component>
				</el-icon>
			</div>
			<div v-if="validStatus">
				<el-result
				:title="msg.title"
				:sub-title="msg.content"
				style="margin-top: 0px;"
				></el-result>
			</div>
			<div v-else>
				<el-result
				icon="error"
				title="校验未通过"
				:sub-title="errorData.length==0?msg.content:''"
				>
				</el-result>
				<div v-if="errorData.length>0">
					<el-table :data="errorData" stripe style="width: 100%; font-size: 15px; color: #FF0000;">
						<el-table-column prop="nodeName" label="节点名称"></el-table-column>
						<el-table-column prop="nodeType" label="节点类型"></el-table-column>
						<el-table-column prop="nodeMsg" label="错误提示"></el-table-column>
					</el-table>
				</div>
			</div>
		</div>
		<div v-else style="padding: 30px 0px;">
			<el-result
				icon="success"
				:title="msg.title"
				:sub-title="msg.content"
			>
				<template #extra>
					<el-button @click="visible=false">继续配置</el-button>
					<el-button type="primary" @click="submit" :loading="submitLoading">保存并发布</el-button>
				</template>
			</el-result>
		</div>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		props: {
			processData: null,
		},
		data() {
			return {
				icon:"el-icon-loading",
				validStep: 0,
				validStatus: true,
				mode: "add",
				submitLoading:false,
				titleMap: {
					add: '流程检查',
					edit: '编辑应用',
					show: '查看'
				},
				visible:false,
				validOptions: [
					{title: '加载配置', description: '', icon: '', status: ''},
					{title: '条件校验', description: '', icon: '', status: ''},
					{title: '审批配置', description: '', icon: '', status: ''},
					{title: '校验完成', description: '', icon: '', status: ''}
				],
				form:{},
				treeData: [],
				approveData: [],
				errorData: [],
				msg: {
					title: '加载中，请稍后...',
					content: '正在读取流程配置信息',
				},
			}
		},
		mounted() {
			// 转成树状结构
			this.getTreeData();
			
			this.getApproveData();

			this.checkProcess();
			this.form.appId = this.$route.query.appId;
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				this.requestParams = [];
				return this
			},
			// 校验流程
			checkProcess(){
				let _this = this;
				_this.errorData = [];
				new Promise(res=>{
					setTimeout(()=>{
						_this.msg = {
							title: '解析中，请稍后...',
							content: '正在解析流程配置信息',
						};
						
						setTimeout(()=>{
							// 判断流程节点数量
							var itemNums = _this.treeData.length;
							if (itemNums == 0) {
								_this.msg = {
									title: '未通过校验',
									content: '请设置至少1个流程节点',
								};
								_this.validStatus = false;
								return;
							} else {
								_this.msg = {
									title: '解析中，请稍后...',
									content: '共有'+ itemNums +'个流程，即将执行校验',
								};
							}
							_this.validStep = 1;
						},1000)

						res();
					},1000)
				}).then(res=>{
					new Promise(res1=>{
						setTimeout(()=>{
							// 条件配置 条件分支如果有 必须设置表单
							_this.getBranchData(this.processData.nodeConfig);
							// var nodeItem = _this.treeData.find(item => item.nodeType == 4);
							// //console.log('nodeItem',nodeItem)
							// _this.msg = {
							// 	title: '校验中，请稍后...',
							// 	content: '条件校验已通过，即将校验审批节点',
							// };
							_this.validStep = 3;
							res1()
						},1000)
					}).then(res1=>{
						if (_this.validStatus){
							_this.msg = {
								title: '校验中，请稍后...',
								content: '正在校验审批流程的配置',
							};
						}
						// 审批流程 必须设置审批人
						_this.approveData.filter(item => {
							console.log('approveData111',item.nodeName);
							var nodeName = item.nodeName;

							if (item.nodeMethod==1 && item.nodeUserList=='[]'){
								var errorItem = {
									nodeName: nodeName,
									nodeType: '审批节点',
									nodeMsg: '未设置审批人'
								}
								_this.errorData.push(errorItem);
								_this.validStatus = false;

							} else if (item.nodeMethod==3 && item.nodeRoleList=='[]'){
								var errorItem = {
									nodeName: nodeName,
									nodeType: '审批节点',
									nodeMsg: '未设置审批角色'
								}
								_this.errorData.push(errorItem);
								_this.validStatus = false;
							}
						});
						
						// 审批节点判断
						if (_this.validStatus){
							_this.msg = {
								title: '恭喜，校验已通过',
								content: '点击发布按钮后，用户可立即使用该流程',
							};
							_this.icon = 'el-icon-check';
							_this.validStep = 4;
						}
					})
				})
			},
			// 获取条件节点
			getBranchData(data){
				// 判断条件
				if (data.conditionNodes){
					// 条件数量
					var branchNums = data.conditionNodes.length;
					// 规则数量
					var childBranchNums = 0;
					data.conditionNodes.forEach(item=>{
						if (item.childNode){
							// 条件分支
							if (item.childNode.type == 4){
								this.getBranchData(item.childNode);
							}
							childBranchNums = childBranchNums + 1;
						}
					});

					if (childBranchNums+1 < branchNums){
						var errorItem = {
							nodeName: "条件分支",
							nodeType: '条件节点',
							nodeMsg: '未设置条件'
						}
						this.errorData.push(errorItem);
						this.validStatus = false;
					}
				}
				if (data.childNode){
					this.getBranchData(data.childNode);
				}
			},
			// 获取审批节点
			getApproveData(){
				var datas = JSON.stringify(this.processData);
				var arrMatch = null;
				var rePattern = new RegExp(
                    /"id":"(node_\d+)","parentId":"([\u4e00-\u9fa5_a-zA-Z0-9]+)","nodeName":"([\u4e00-\u9fa5_a-zA-Z0-9]+)","type":1,"setType":([0-9]),"nodeUserList":([\s\S]*?),"nodeRoleList":([\s\S]*?),"examineLevel":1/,
                    "gi"
                );
				while (arrMatch = rePattern.exec(datas)) {
					var nodeItem = {
						nodeId: arrMatch[1],
						parentId: arrMatch[2],
						nodeName: arrMatch[3],
						nodeType: 1,
						nodeMethod: arrMatch[4],
						nodeUserList: arrMatch[5],
						nodeRoleList: arrMatch[6]
					}
					this.approveData.push(nodeItem);
				}
			},
			// 转换成树状结构
			getTreeData(){
				//console.log('this.this.processData',this.processData)
				var datas = JSON.stringify(this.processData);
				//console.log('datas',datas);
                var arrMatch = null;
				var rePattern = new RegExp(
                    /"id":"(node_\d+)","parentId":"([\s\S]*?)","nodeName":"([\s\S]*?)","type":([0-9])/,
                    "gi"
                );
                while (arrMatch = rePattern.exec(datas)) {
					var nodeItem = arrMatch[0];
					var nodeId = arrMatch[1];
					var parentId =  arrMatch[2];
					var nodeName = arrMatch[3];
					var nodeType = arrMatch[4];

					if (!(/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/).test(nodeName)){
						console.log('AAAAAA',nodeItem)
						var childReg = new RegExp(
							/"childNode":{"id":"(node_\d+)","parentId":"([\s\S]*?)","nodeName":"([\s\S]*?)","type":([0-9])/,
							"gi"
						);
						var childMatch = childReg.exec(nodeItem);
						if (childMatch != null){
							nodeId = childMatch[1];
							parentId =  childMatch[2];
							nodeName = childMatch[3];
							nodeType = childMatch[4];
						}
					}

					var nodeItem = {
						nodeId: nodeId,
						parentId: parentId,
						nodeName: nodeName,
						nodeType: nodeType,
					}
					this.treeData.push(nodeItem);
                }
			},
			// 提交流程
			async submit() {
				this.submitLoading =true;
				this.form.flowTemplate = JSON.stringify(this.processData);
				let res ={}
				if (this.form.flowVersion == null){
					res = await this.$API.app.flow.addFlow.post(this.form)
				}else {
					res = await this.$API.app.flow.updateFlow.put(this.form)
				}
				if (res.code == 200){
					this.$message.success("保存成功")
					this.$parent.refresh(res.data)
					this.submitLoading = false;
					this.visible = false;
				}else {
					this.$message.error("保存失败")
					this.submitLoading = false;
				}
			},
			// 设置表单版本
			setData(data){
				this.form.flowVersion=data;
			}
		}
	}
</script>

<style>
.el-dialog__body{
	padding: 20px;
	padding-right: 30px;
}
.steps{
	width: 100%;
	margin-left: 40px;
	padding: 0px;
	background: #FFF;
}
.el-collapse-item__header{
	font-weight: bolder;
	font-size: 16px;
	margin-top: 10px;
}

.app-icon {
	width: 120px;
	fill: rgba(253, 253, 253, 0.65) !important;
	background-color: rgba(255, 255, 255, 0.94);
	padding: 30px;
	border-radius: 12px;
}
</style>
